package com.example.administrator.funchat.fragment;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.funchat.Contans.Config;
import com.example.administrator.funchat.R;
import com.example.administrator.funchat.util.WebService;
import com.example.administrator.funchat.util.WebServicePost;
import com.example.administrator.funchat.activity.RegisterLoginActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/21.
 */
public class RegisterFragment extends Fragment implements View.OnClickListener {


    //登录按钮
    private Button registerBtton;
    // 显示用户名和密码
    EditText username, password;
    // 创建等待框
    private ProgressDialog dialog;
    // 返回的数据
    private String info;
    // 返回主线程更新数据
    private static Handler handler = new Handler();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.register_fragment, container, false);
        // 获取控件
        registerBtton = (Button) view.findViewById(R.id.register_button);
        username = (EditText) view.findViewById(R.id.registerUser);
        password = (EditText) view.findViewById(R.id.registerPassWord);
        //设置按钮监听器
        registerBtton.setOnClickListener(this);

        return view;
    }


    @Override
    public void onClick(View view) {

        // 检测网络，无法检测wifi
        if (!checkNetwork(view)) {
            Toast toast = Toast.makeText(view.getContext(), "网络未连接", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();

        }
        //提示框
        dialog = new ProgressDialog(view.getContext());
        dialog.setMessage("正在注册，请稍后...");
        dialog.setCancelable(false);
        dialog.show();
        //创建子线程,进行Post传输
        new Thread(new MyThread()).start();

    }

    private boolean checkNetwork(View view) {
        ConnectivityManager connManager = (ConnectivityManager) view.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connManager.getActiveNetworkInfo() != null) {
            return connManager.getActiveNetworkInfo().isAvailable();
        }
        return false;
    }

    // 子线程发送请求，主线程修改
    private class MyThread implements Runnable {
        @Override
        public void run() {

            final RequestParams params = new RequestParams();
            params.addBodyParameter("phone", username.getText().toString());
            //检查账号是否已经注册
            new HttpUtils().send(HttpRequest.HttpMethod.POST, Config.IS_REGISTER, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {

                    if (responseInfo.result.equals("ok")) {
                        //未注册时
                        dialog.dismiss();
                        Toast toast = Toast.makeText(getActivity(), "该账号已注册", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                    } else {
                        //未注册时

                        RequestParams p = new RequestParams();
                        p.addBodyParameter("phone", username.getText().toString());
                        p.addBodyParameter("password", password.getText().toString());
                        //注册
                        new HttpUtils().send(HttpRequest.HttpMethod.POST, Config.REGISTER, p, new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                //请求服务器成功
                                dialog.dismiss();
                                if (responseInfo.result.equals("ok")) {
                                    //注册成功
                                    Toast toast = Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                } else {
                                    //注册失败
                                    Toast toast = Toast.makeText(getActivity(), "注册失败，请重新操作", Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            }

                            @Override
                            public void onFailure(HttpException e, String s) {
                                dialog.dismiss();
                                Toast toast = Toast.makeText(getActivity(), "注册失败,无法连接到服务器", Toast.LENGTH_SHORT);
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();
                            }
                        });
                        //发送手机号码和密码到服务端
                        // 发送指令和信息
                       /* String address = "/MyChat/UserServlet?options=register" + "&phone=" + username.getText().toString() + "&password=" + password.getText().toString();
                        info = WebService.executeHttpGet(address);
                        if (info == null) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                    Toast toast = Toast.makeText(getActivity(), "注册失败,无法连接到服务器", Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            });
                        } else if (info.equals("ok")) {
                            Toast toast = Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            final Map<String, String> params = new HashMap<>();
                            params.put("phone", username.getText().toString());
                            params.put("password", password.getText().toString());
                            String centerpath = "/MyChat/UserServlet?options=register";
                            info = WebServicePost.executeHttpPost(params, centerpath);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                    RegisterLoginActivity activity = (RegisterLoginActivity) getActivity();
                                    FragmentManager fm = activity.getFragmentManager();
                                    FragmentTransaction transation = fm.beginTransaction();
                                    // LoginFragment loginfragment = new LoginFragment(params);
                                    // transation.replace(R.id.framelayout, loginfragment);
                                    *//* ((RegisterLoginActivity) getActivity()).denglu.setBackgroundResource(R.drawable.dlwenben);
                                    ((RegisterLoginActivity) getActivity()).zhuce.setText("注册");
                                    ((RegisterLoginActivity) getActivity()).zhuce.setTextColor(0xFFD77712);
                                    transation.commit();*//*
                                }
                            });
                        } else {
                            dialog.dismiss();
                            Toast toast = Toast.makeText(getActivity(), "注册失败", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }*/
                    }
                }


                @Override
                public void onFailure(HttpException e, String s) {
                    Toast toast = Toast.makeText(getActivity(), "服务器异常", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            });
        }


//    private String parseJSONWithJSONObject(String info) {
//        String rephone = null;
//        try {
//            JSONArray jsonArray = new JSONArray(info);
//            for (int i = 0; i <jsonArray.length();i++){
//                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                String id = jsonObject.getString("id");
//                String password = jsonObject.getString("password");
//                String phone = jsonObject.getString("phone");
//
//                rephone = phone;
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return rephone;
//    }
    }
}
